<template>
	<view class="grid-container">
		<view class="header" style="width: 100%;">
            <view style="width: calc(100% - 100px);flex-shrink: 0;">
                <u-subsection :list="list" :current="searchParams.productState" keyName="name" @change="onChangeSubSection"></u-subsection>
            </view>
            <view style="width: 100px;flex-shrink: 0;padding: 0 8px;box-sizing: border-box;">
                <u-button type="primary" @click="onShowBtn" icon="search" text="查询"></u-button>
            </view>
        </view>
        <jk-table @pull="onPull" :cellStyle="cellStyle" width="60" type="operation" @onDetailEnquiry="onDetailEnquiry" stripe :height="tableHeight - 124" :table-header="tableHeader" :table-data="tableData"></jk-table>
        <more-search
            :popup-state="moreSearchState"
            @close="(e) => moreSearchState = e"
            @confirm="onConfirmOfMoreSearch"
        ></more-search>
		</view>
</template>

<script>
	import jkTable from "../../jk-components/jk-table";
    import {
        reportProductionOrderTracking,
        reportProductionOrderTrackingCount,
        systemUserColumnConfigGet
    } from "../../api/index.js";
    import {isLastPage, pageConfig, showLoading} from "../../utils/jk-utils.js";
    import loadingMore from "../../mixins/loading-more";
    import moreSearch from './components/moreSearch';
    export default {
        mixins: [loadingMore],
        components: {
            moreSearch,
            jkTable,
        },
        data() {
            return {
                apiConfig: {
                    list: reportProductionOrderTracking
                },
                moreSearchState: false,
                list: [
                    { id: 0, name: '待生产', color: '#ff9900' },
                    { id: 1, name: '生产中', color: '#2b85e4' },
                    { id: 2, name: '已完成', color: '#19be6b' }
                ],
                productStateList: [
                    { id: 0, name: '待生产', color: '#ff9900' },
                    { id: 1, name: '生产中', color: '#2b85e4' },
                    { id: 2, name: '已完成', color: '#19be6b' }
                ],
                current: 1,
                interVal: {},
                countVal: 0,
                tableHeight: 0,
                show:false,
                searchParams:{
                    pageNo:1,
                    pageSize: pageConfig.pageSize,
                    customerName:'',
                    productName:'',
                    productState: 1,
                    ifTest: false,
                    totalCount: 0
                },
                tableHeader:null,
                tableData:[],
                customIptStyle: {
                    border: 'solid 1px #dcdee2'
                },
            };
        },
         onLoad() {
            this.getDependentData();
        },
        onShow() {
            this.landscape();
            // 用于直接回到手机桌面再进入时重新启动定时任务
            this.runData();
        },
        onHide(){
            this.clearInterVal()
        },
        onUnload() {
            this.clearInterVal()
        },
        methods: {
            onConfirmOfMoreSearch(item) {
                this.searchParams = {
                    ...this.searchParams,
                    ...item
                };
                this.moreSearchState = false;
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onShowBtn() {
                this.moreSearchState = true;
            },
            onPull() {
                this.getMore();
            },
            getMore() {
                if (!isLastPage(this.searchParams.totalCount, this.searchParams.pageNo, this.searchParams.pageSize)) {
                    this.searchParams.pageNo++;
                    showLoading(true);
                    return this.apiConfig['list'](this.searchParams).then(res => {
                        showLoading(false);
                        if (res.data.status === 200) {
                            this.$set(this.searchParams, 'totalCount', res.data.count);
                            let arr = res.data.res ? res.data.res.map(x => {
                                x.batchCode = x.batchList ? x.batchList.map(k => k.batchCode).join(',') : '';
                                x.coarseSandList = x.coarseSandList ? x.coarseSandList.filter(v => v.typeName === '粗纱').map(x => x.productName).join(',') : '';
                                x.paperTubeList = x.batchList ? x.batchList.map(u => u.paperTubeList[0]?.name).join(',') : '';
                                x.progress = x.orderQty ? `${parseInt((( x.completionQty || 0) / x.orderQty) * 100)}%` : 0 ;
                                x.openNum = x.processList ? x.processList.find(x => x.processCode === "XS") ? x.processList.find(x => x.processCode === "XS").productOrderMachineList.length : '0' : '0' ;
                                return x;
                            }) : [];
                            arr.forEach(x => {
                                this.tableData.push(x);
                            })
                        }
                    })
                } else {
                    // wx.showToast({ title: '没有更多了!', icon: 'error', duration: 500 })
                    this.isNoMore = true;
                }
            },
            onChangeSubSection(e) {
                this.tableData = [];
                this.$set(this.searchParams, 'pageNo', 1);
                this.$set(this.searchParams, 'productState', e);
                this.getListRequest();
            },
            getStateBarCountRequest() {
                return reportProductionOrderTrackingCount({
                    ifTest: false
                }).then(res => {
                    if (res.data.status === 200) {
                        this.list = this.productStateList.map(x => {
                            x.count = 0;
                            res.data.res.forEach(k => {
                                if (x.id === k.productState) {
                                    x.name = `${x.name}(${k.count})`;
                                }
                            });
                            return x;
                        });
                    } else {
                        this.list = this.productStateList.map(x => {
                            x.count = 0;
                            return x;
                        });
                    }
                });
            },
            async getDependentData() {
                showLoading(true);
                await this.getSystemInfo();
                await this.getHeaderRequest();
                await this.getStateBarCountRequest();
                await this.getListRequest();
                showLoading(false);
                this.runData();
            },
            cellStyle({row}){
                return {
                    // backgroundColor: row.ifOpen ? '#1890ff' : '',
                    // color: row.ifOpen ? '#ffffff' : ''
                };
            },
            onDetailEnquiry(row, index, column){
                uni.setStorageSync('rowKey', row);
                wx.navigateTo({
                    url: `../summaryDetail/index`,
                });
            },
            runData() {
                clearInterval(this.interVal);
                this.interVal = setInterval(() => {
                        this.getListRequest();
                }, 10000);
            },
            clearInterVal() {
                clearInterval(this.interVal);
            },
            getSystemInfo() {
                let _this = this;
                return new Promise(((resolve, reject) => {
                    uni.getSystemInfo({
                        success(res) {
                            resolve();
                            _this.windowHeight = res.windowHeight;
                            _this.tableHeight = res.windowWidth - 0;
                        },
                        error(err) {
                            reject(err)
                        }
                    });
                }))
            },
            // 横屏展示
            landscape() {
                uni.setPageOrientation({
                    orientation: 'landscape'
                });
            },
            getListRequest(){
                return this.apiConfig['list'](this.searchParams).then(res=>{
                        if(res.data.status === 200){
                            this.$set(this.searchParams, 'totalCount', res.data.count);
                            this.tableData = res.data.res ? res.data.res.map(x => {
                                 x.batchCode = x.batchList ? x.batchList.map(k => k.batchCode).join(',') : '';
                                 x.coarseSandList = x.coarseSandList ? x.coarseSandList.filter(v => v.typeName === '粗纱').map(x => x.productName).join(',') : '';
                                 x.paperTubeList = x.batchList ? x.batchList.map(u => u.paperTubeList[0]?.name).join(',') : '';
                                 x.progress = x.orderQty ? `${parseInt((( x.completionQty || 0) / x.orderQty) * 100)}%` : 0 ;
                                 x.openNum = x.processList ? x.processList.find(x => x.processCode === "XS") ? x.processList.find(x => x.processCode === "XS").productOrderMachineList.length : '0' : '0' ;
                              return x;
                              }) : [];
                        }
                })
            },
            getHeaderRequest(){
                showLoading(true);
                return systemUserColumnConfigGet({
                    path:'orderMonitorReport',
                    filterShow:true
                }).then(res=>{
                    if(res.data.status === 200){
                        showLoading(false);
                        let resData = res.data.res;
                        let arr = [];
                        if (resData && resData.columnConfigList) {
                            arr = resData.columnConfigList.find(x => x.code === 'wechat') ? resData.columnConfigList.find(x => x.code === 'wechat').itemList : [];
                        }
                        arr.push({type:'operation',label: '操作',renders:[{name:'开台明细',func:'onDetailEnquiry'}]})
                        this.tableHeader = arr.map(x => {
                            if(x.keyName === 'processList'){
                                x.keyName = 'openNum'
                            }
                            x.key = x.keyName;
                            return x;
                        });
                    }
                })
            }
        }
    };
</script>

<style scoped lang="scss">
.grid-container {
	background-color: #f8f8f9;
	.header {
		width: 100%;
		border-radius: 5rpx;
		background-color: #fff;
		z-index: 999;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: space-around;
		position: static;
		top: 0px;
		botto: 5rpx;
		.header-left {
			display: flex;
			align-items: center;
			.in-production,
			.to-be-produced {
				margin-left: 10rpx;
				display: flex;
				align-items: center;
				text {
					display: inline-block;
					width: 15rpx;
					height: 10rpx;
					background-color: #3c9cff;
					margin-right: 3rpx;
				}
			}
		}
		.header-right {
			display: flex;
			justify-content: space-between;
			align-items: center;
			.search {
				display: flex;
				align-items: center;
				justify-content: space-between;
				.my-input {
					flex: 1 !important;
				}
			}
		}
	}
}
</style>
